package com.practice;

import cn.hutool.extra.spring.SpringUtil;
import jakarta.annotation.Resource;
import liquibase.integration.spring.SpringLiquibase;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ResourceLoader;

import javax.sql.DataSource;

@Configuration
public class LiquibaseConfiguration implements ApplicationRunner {

    @Resource
    private DataSource dataSource;
    @Resource
    private ResourceLoader resourceLoader;

    @Value("${liquibase.enabled:false}")
    private Boolean enabled;

    @Value("${liquibase.databaseChangeLogTable:}")
    private String databaseChangeLogTable;

    @Value("${liquibase.databaseChangeLogLockTable:}")
    private String databaseChangeLogLockTable;

    @Value("${liquibase.change-log:}")
    private String changeLog;

    @Lazy
    @Primary
    @Bean
    public LiquibaseProperties liquibaseProperties() {
        LiquibaseProperties liquibaseProperties = new LiquibaseProperties();
        liquibaseProperties.setEnabled(false);
        return liquibaseProperties;
    }


    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (!enabled) {
            return;
        }
        LiquibaseProperties liquibaseProperties = SpringUtil.getApplicationContext().getBean(LiquibaseProperties.class);
        SpringLiquibase liquibase = new SpringLiquibase();
        liquibase.setChangeLog(changeLog);
        liquibase.setContexts(liquibaseProperties.getContexts());
        liquibase.setDataSource(dataSource);
        liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
        liquibase.setDropFirst(liquibaseProperties.isDropFirst());
        liquibase.setShouldRun(true);
        liquibase.setChangeLogParameters(liquibaseProperties.getParameters());
        liquibase.setResourceLoader(resourceLoader);
        liquibase.setDatabaseChangeLogTable(databaseChangeLogTable);
        liquibase.setDatabaseChangeLogLockTable(databaseChangeLogLockTable);
        liquibase.afterPropertiesSet();
    }
}